package com.treetao.union.mall.api.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.github.binarywang.wxpay.bean.notify.WxPayOrderNotifyResult;
import com.treetao.union.core.tencent.microapp.TencentMicroappPayService;
import com.treetao.union.core.tencent.microapp.option.MicroappOption;
import com.treetao.union.core.util.ToolUtil;
import com.treetao.union.db.Const;
import com.treetao.union.db.Const.OrderRecord;
import com.treetao.union.db.Const.OrderStatus;
import com.treetao.union.db.model.MallOrder;
import com.treetao.union.db.model.vo.RestResponse;
import com.treetao.union.db.pojo.SettingTypeWeixin;
import com.treetao.union.db.service.MallOrderService;
import com.treetao.union.mall.api.base.BaseApiController;
import com.treetao.union.mall.api.service.TencentDbService;
import com.treetao.union.mall.api.vo.req.ReqParam;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@RestController
@RequestMapping("/mall/pay")
public class MallPayController extends BaseApiController {
	@Autowired
	private TencentMicroappPayService microappPayService;
	@Autowired
	private TencentDbService tencentDbService;
	@Autowired
	private MallOrderService orderService;

	@PostMapping("/create")
	public RestResponse unifiedOrder(@RequestBody ReqParam param, HttpServletRequest req) {
		Long orderno = param.getLong("orderno", false);
		MallOrder order = orderService.getMallOrder(orderno);
		if (order == null) {
			return RestResponse.failure("订单不存在");
		}
		Long userId = getWxuidFromToken();
		if (userId.longValue() != order.getUserId().longValue()) {
			return RestResponse.failure("无权限订单");
		}
		int totalFee = order.getPriceReal().intValue() * 100;// 单位：分

		SettingTypeWeixin weixin = tencentDbService.getConfigTencentWeixin();
		MicroappOption option = new MicroappOption();
		option.setAppId(weixin.getWxAppid());
		option.setMchId(weixin.getWxMchId());
		option.setMchKey(weixin.getWxMchKey());
		option.setSecret(weixin.getWxSecret());
		option.setNotifyUrl(weixin.getWxPayNotifyUrl());
		microappPayService.config(option);

		Map<String, Object> result = microappPayService.newOrder(getOpenidFromToken(), String.valueOf(orderno),
				"订单-" + orderno, totalFee, ToolUtil.getClientIp(req));
		return RestResponse.success(result);
	}

	/**
	 * 客户端收到支付成功时,调用该接口表示支付成功
	 * 
	 * @param param
	 * @return
	 */
	@PostMapping("/prenotify")
	public RestResponse prenotify(@RequestBody ReqParam param) {
		Long orderno = param.getLong("orderno", false);
		Long userId = getWxuidFromToken();
		MallOrder order = orderService.getMallOrder(orderno);
		if (order == null) {
			return RestResponse.failure("订单不存在");
		}
		if (userId.longValue() != order.getUserId().longValue()) {
			return RestResponse.failure("无权限订单");
		}
		return RestResponse.success(orderService.changeOrderStatus(orderno, OrderStatus.PREPAYED,OrderRecord.PAYED));
	}

	@PostMapping("/notify")
	public String notify(HttpServletRequest req) {
		String xml = null;
		try {
			xml = IOUtils.toString(req.getInputStream(), req.getCharacterEncoding());
			WxPayOrderNotifyResult pnr = microappPayService.notifyCallbackParse(xml);
			String outTradeNo = pnr.getOutTradeNo();// 本平台订单号
			Integer totalFee = pnr.getTotalFee();// 单位：分

			MallOrder order = orderService.getMallOrder(Long.valueOf(outTradeNo));
			if (order == null) {
				log.error("订单不存在,通知订单号：{}", outTradeNo);
				return microappPayService.genPayCallbackContent(false);
			}
			Double priceReal = order.getPriceReal() * 100;
			if (priceReal.intValue() != totalFee.intValue()) {
				log.error("金额对应不上，订单金额：{}分，通知金额：{}分", priceReal, totalFee);
				return microappPayService.genPayCallbackContent(false);
			}
			int status = order.getStatus();
			if (status != Const.OrderStatus.PREPAYED.getValue()) {//不是当前状态，不能处理
				log.error("订单状态为：{}，不能处理", status);
				return microappPayService.genPayCallbackContent(false);
			}
			boolean flag = orderService.payNotifyedWeixin(Long.valueOf(outTradeNo), priceReal, xml);
			if(flag) {
				return microappPayService.genPayCallbackContent(true);
			} else {
				log.error("保存到数据库失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return microappPayService.genPayCallbackContent(false);
	}
}
